# src/api/prescriptions.py
from fastapi import APIRouter, HTTPException, status, Query
from typing import List
from ..models.schemas import PrescriptionCreate, PrescriptionOut
from .. import crud
router = APIRouter(tags=["prescriptions"])


@router.post("", response_model=PrescriptionOut, status_code=status.HTTP_201_CREATED)
def create_prescription(payload: PrescriptionCreate):
    try:
        pres = crud.create_prescription(payload.dict())
        # return the prescription header; items available via GET
        return pres
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("", response_model=List[PrescriptionOut])
def list_prescriptions(limit: int = 50, offset: int = 0):
    rows = crud.list_prescriptions(limit=limit, offset=offset)
    return rows


@router.get("/{prescription_id}", response_model=PrescriptionOut)
def get_prescription(prescription_id: int):
    pres = crud.get_prescription(prescription_id)
    if not pres:
        raise HTTPException(status_code=404, detail="Prescription not found")
    return pres
